﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using FMS.Formulation.Licensing.License;

namespace WindowsFormsApp1
{

    internal class ReadCertificate
    {
        private bool _isTempActivation = false;

        private string _errorMessage = string.Empty;

        private string _activationCode = string.Empty;

        private string _licenseData = string.Empty;

        public bool IsTempActivation => _isTempActivation;

        public string ErrorMessage => _errorMessage;

        public bool ServerDataBad
        {
            get
            {
                if (_errorMessage.Trim().Length != 0 || _activationCode.Trim().Length == 0)
                {
                    return true;
                }
                return false;
            }
        }

        public string LicenseData
        {
            get
            {
                return _licenseData;
            }
            set
            {
                _licenseData = value;
            }
        }

        public void DestroyCertificateSignature(string CertificateURL)
        {
            FileInfo fileInfo = new FileInfo(CertificateURL);
            fileInfo.IsReadOnly = false;
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(CertificateURL);
            XmlNodeList elementsByTagName = xmlDocument.GetElementsByTagName("SignatureValue");
            if (elementsByTagName.Count > 0)
            {
                elementsByTagName.Item(0).ChildNodes.Item(0).Value = "Disabled";
                xmlDocument.Save(CertificateURL);
            }
            else
            {
                TrialLicense trialLicense = new TrialLicense();
                trialLicense.DestroyTrialLicense(xmlDocument, CertificateURL);
            }
        }

        public bool ReadLicenseCertificate(string CertificateURL, FMS.Formulation.Licensing.License.License theLicense, out bool LicenseIsTrial, out bool IsDisabled)
        {
            LicenseIsTrial = false;
            IsDisabled = false;
            XmlDocument xmlDocument = new XmlDocument();
            try
            {
                xmlDocument.Load(CertificateURL);
            }
            catch
            {
                return false;
            }
            theLicense.SecurityFileLocation = CertificateURL;
            return ReadLicenseCertificateXML(xmlDocument, theLicense, out LicenseIsTrial, out IsDisabled);
        }

        public bool ReadLicenseCertificateXML(XmlDocument xdoc, FMS.Formulation.Licensing.License.License theLicense, out bool LicenseIsTrial, out bool IsDisabled)
        {
            LicenseIsTrial = false;
            IsDisabled = false;
            XmlNodeList elementsByTagName = xdoc.GetElementsByTagName("UniqueInstallation");
            if (elementsByTagName.Count == 0)
            {
                _isTempActivation = true;
            }
            else
            {
                _isTempActivation = false;
            }
            string empty = string.Empty;
            TrialLicense trialLicense = new TrialLicense();
            LicenseIsTrial = trialLicense.LicenseIsATrial(xdoc);
            if (LicenseIsTrial)
            {
                empty = trialLicense.GetLicenseData(xdoc, ref IsDisabled);
            }
            else
            {
                elementsByTagName = xdoc.GetElementsByTagName("ServerData");
                if (elementsByTagName.Count == 0)
                {
                    return false;
                }
                string value = elementsByTagName.Item(0).ChildNodes.Item(0).Value;
                UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
                byte[] bytes = Convert.FromBase64String(value);
                empty = unicodeEncoding.GetString(bytes);
                elementsByTagName = xdoc.GetElementsByTagName("SignatureValue");
                if (elementsByTagName.Count > 0)
                {
                    string value2 = elementsByTagName.Item(0).ChildNodes.Item(0).Value;
                    if (value2 == "Disabled")
                    {
                        IsDisabled = true;
                    }
                }
            }
            if (empty.Length < 1)
            {
                return false;
            }
            _licenseData = empty;
            string[] array = empty.Split("\n".ToCharArray());
            int num = 0;
            _errorMessage = string.Empty;
            theLicense.InitializeLicense();
            _activationCode = theLicense.ActivationCode;
            string[] array2 = array;
            foreach (string text in array2)
            {
                if (text.StartsWith("VerifyLicense", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (text.Substring(text.IndexOf("=") + 1).Trim() == "True")
                    {
                        theLicense.VerifyLicense = true;
                    }
                    else
                    {
                        theLicense.VerifyLicense = false;
                    }
                    num++;
                    continue;
                }
                if (text.StartsWith("LastVerifiedDate", StringComparison.InvariantCultureIgnoreCase))
                {
                    string text2 = text.Substring(text.IndexOf("=") + 1).Trim();
                    if (text2.Trim().Length > 0)
                    {
                        try
                        {
                            theLicense.LastVerifiedDate = DateTime.ParseExact(text2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                        }
                        catch
                        {
                        }
                    }
                    num++;
                    continue;
                }
                if (text.StartsWith("ActivationCode", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.ActivationCode = text.Substring(text.IndexOf("=") + 1).Trim();
                    _activationCode = theLicense.ActivationCode;
                    num++;
                    continue;
                }
                if (text.StartsWith("Error Message", StringComparison.InvariantCultureIgnoreCase))
                {
                    _errorMessage = text.Substring(text.IndexOf("=") + 1).Trim();
                    num++;
                    continue;
                }
                if (text.StartsWith("CName", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.CompanyName = text.Substring(text.IndexOf("=") + 1).Trim();
                    num++;
                    continue;
                }
                if (text.StartsWith("TimeBomb", StringComparison.InvariantCultureIgnoreCase))
                {
                    string text3 = text.Substring(text.IndexOf("=") + 1).Trim();
                    if (text3.Trim().Length > 0)
                    {
                        try
                        {
                            theLicense.ExpirationDate = DateTime.ParseExact(text3, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                        }
                        catch
                        {
                        }
                    }
                    num++;
                    continue;
                }
                if (text.StartsWith("SerialNum", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.LicenseSerialNumber = Convert.ToInt32(text.Substring(text.IndexOf("=") + 1), CultureInfo.InvariantCulture);
                    num++;
                    continue;
                }
                if (text.StartsWith("MaxUsers", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.MaximumUsers = Convert.ToInt32(text.Substring(text.IndexOf("=") + 1), CultureInfo.InvariantCulture);
                    num++;
                    continue;
                }
                if (text.StartsWith("AppVer", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.ApplicationVersion = Convert.ToInt32(text.Substring(text.IndexOf("=") + 1), CultureInfo.InvariantCulture);
                    num++;
                    continue;
                }
                if (text.StartsWith("PlugSer", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.ValidationDays = Convert.ToInt32(text.Substring(text.IndexOf("=") + 1), CultureInfo.InvariantCulture);
                    num++;
                    continue;
                }
                if (text.StartsWith("PlugNo", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.GracePeriod = Convert.ToInt32(text.Substring(text.IndexOf("=") + 1), CultureInfo.InvariantCulture);
                    num++;
                    continue;
                }
                if (text.StartsWith("MasterCo", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.MasterCompany = Convert.ToInt32(text.Substring(text.IndexOf("=") + 1), CultureInfo.InvariantCulture);
                    num++;
                    continue;
                }
                if (text.StartsWith("CustID", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (text.StartsWith("CustIDDesc", StringComparison.InvariantCultureIgnoreCase))
                    {
                        theLicense.CustomerIDDescription = text.Substring(text.IndexOf("=") + 1).Trim();
                        num++;
                    }
                    else
                    {
                        theLicense.CustomerID = text.Substring(text.IndexOf("=") + 1).Trim();
                        num++;
                    }
                    continue;
                }
                if (text.StartsWith("Comment", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.Comment = text.Substring(text.IndexOf("=") + 1).Trim();
                    num++;
                    continue;
                }
                if (text.StartsWith("PrevDate", StringComparison.InvariantCultureIgnoreCase))
                {
                    string text4 = text.Substring(text.IndexOf("=") + 1).Trim();
                    if (text4.Trim().Length > 0)
                    {
                        theLicense.LicenseLastUpdated = DateTime.ParseExact(text4, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        theLicense.LicenseLastUpdated = DateTime.Now;
                    }
                    num++;
                    continue;
                }
                if (text.StartsWith("MaxiSpec", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.MaximumIngredientsInSpec = Convert.ToInt16(text.Substring(text.IndexOf("=") + 1), CultureInfo.InvariantCulture);
                    num++;
                    continue;
                }
                if (text.StartsWith("MaxNSpec", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.MaximumNutrientsInSpec = Convert.ToInt16(text.Substring(text.IndexOf("=") + 1), CultureInfo.InvariantCulture);
                    num++;
                    continue;
                }
                if (text.StartsWith("NoNuts", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.MaximumNutrientsInSystem = Convert.ToInt16(text.Substring(text.IndexOf("=") + 1), CultureInfo.InvariantCulture);
                    num++;
                    continue;
                }
                if (text.StartsWith("MaxIngs", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.MaximumIngredientsInSystem = Convert.ToInt16(text.Substring(text.IndexOf("=") + 1), CultureInfo.InvariantCulture);
                    num++;
                    continue;
                }
                if (text.StartsWith("ArchOn", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.MaximumArchiveVersionsAllowed = Convert.ToInt16(text.Substring(text.IndexOf("=") + 1), CultureInfo.InvariantCulture);
                    num++;
                    continue;
                }
                if (text.StartsWith("DisSwtch", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (text.Substring(text.IndexOf("=") + 1).Trim() == "True")
                    {
                        theLicense.ProgramIsDisabled = true;
                    }
                    else
                    {
                        theLicense.ProgramIsDisabled = false;
                    }
                    num++;
                    continue;
                }
                if (text.StartsWith("MaxMult", StringComparison.InvariantCultureIgnoreCase))
                {
                    theLicense.MaximumMultiblendUsers = Convert.ToInt16(text.Substring(text.IndexOf("=") + 1), CultureInfo.InvariantCulture);
                    num++;
                    continue;
                }
                if (text.StartsWith("Switch", StringComparison.InvariantCultureIgnoreCase))
                {
                    int num2 = array.GetUpperBound(0) - num;
                    for (int j = 0; j < num2; j++)
                    {
                        int num3 = array[j + num].IndexOf(":");
                        int num4 = array[j + num].IndexOf("-");
                        Switch @switch = new Switch();
                        @switch.SwitchID = Convert.ToInt32(array[j + num].Substring(8, 3), CultureInfo.InvariantCulture);
                        DateTime expirationDate = DateTime.MinValue;
                        if (num4 > 0 && num4 < num3 + 10)
                        {
                            string text5 = array[j + num].Substring(num4 - 4, 10);
                            if (text5.Trim() != strinsg.Empty)
                            {
                                string s = array[j + num].Substring(num4 - 4, 10);
                                expirationDate = DateTime.ParseExact(s, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                            }
                        }
                        @switch.ExpirationDate = expirationDate;
                        theLicense.Switches.Add(@switch);
                    }
                    break;
                }
                num++;
            }
            if (LicenseIsTrial)
            {
                try
                {
                    if (theLicense.LastVerifiedDate != theLicense.LicenseLastUpdated)
                    {
                        return false;
                    }
                    if (theLicense.ValidationDays != theLicense.GracePeriod)
                    {
                        return false;
                    }
                    TimeSpan timeSpan = theLicense.ExpirationDate - DateTime.Now;
                    if (timeSpan.Days > theLicense.ValidationDays)
                    {
                        return false;
                    }
                    if (timeSpan.Days > 90)
                    {
                        return false;
                    }
                }
                catch
                {
                    return false;
                }
                theLicense.ValidationDays = 0;
                theLicense.GracePeriod = 0;
            }
            else if (theLicense.GracePeriod == 4 || theLicense.GracePeriod < 0)
            {
                theLicense.GracePeriod = 0;
                theLicense.ValidationDays = 0;
            }
            return true;
        }
    }

}
